#!/usr/bin/env bash

# 默认配置
DEFAULT_IMAGE_NAME="echo"
REGISTRY="registry.cn-hangzhou.aliyuncs.com"
NAMESPACE="my_public_images"
BUILD_CONTEXT="."

# 函数：输出错误并退出
error() {
  echo -e "\033[0;31m[ERROR] $1\033[0m" >&2
  exit 1
}

# 函数：输出信息
info() {
  echo -e "\033[0;32m[INFO] $1\033[0m"
}

# 解析命令行参数
while [[ $# -gt 0 ]]; do
  case $1 in
    -n|--name)
      IMAGE_NAME="$2"
      shift 2
      ;;
    -v|--version)
      VERSION="$2"
      shift 2
      ;;
    -r|--registry)
      REGISTRY="$2"
      shift 2
      ;;
    -ns|--namespace)
      NAMESPACE="$2"
      shift 2
      ;;
    -c|--context)
      BUILD_CONTEXT="$2"
      shift 2
      ;;
    -h|--help)
      echo "用法: $0 [选项]"
      echo "选项:"
      echo "  -n, --name        镜像名称 (默认: $DEFAULT_IMAGE_NAME)"
      echo "  -v, --version     镜像版本 (默认: latest)"
      echo "  -r, --registry    镜像仓库地址 (默认: $REGISTRY)"
      echo "  -ns, --namespace  命名空间 (默认: $NAMESPACE)"
      echo "  -c, --context     构建上下文路径 (默认: $BUILD_CONTEXT)"
      echo "  -h, --help        显示此帮助信息"
      exit 0
      ;;
    *)
      error "未知参数: $1"
      ;;
  esac
done

# 设置默认值
IMAGE_NAME=${IMAGE_NAME:-$DEFAULT_IMAGE_NAME}
VERSION=${VERSION:-latest}

# 动态生成 Dockerfile 名称
DOCKERFILE="${IMAGE_NAME}.dockerfile"

# 验证 Dockerfile 是否存在
if [ ! -f "$DOCKERFILE" ]; then
  error "Dockerfile 不存在: ${DOCKERFILE}"
fi

# 构建完整镜像标签
TAG="${REGISTRY}/${NAMESPACE}/${IMAGE_NAME}:${VERSION}"

# 检查 Docker 是否运行
info "检查 Docker 服务..."
docker info >/dev/null 2>&1 || error "Docker 未运行，请启动 Docker 服务"

# 检查是否登录到镜像仓库
info "检查镜像仓库登录状态..."
if ! docker info | grep -q "${REGISTRY}"; then
  info "未登录到 ${REGISTRY}，尝试登录..."
  docker login "${REGISTRY}" || error "登录失败，请检查凭证"
fi

# 构建镜像
info "开始构建镜像: ${TAG}"
docker build -f "${DOCKERFILE}" \
  --build-arg BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ') \
  --build-arg VERSION="${VERSION}" \
  --build-arg IMAGE_NAME="${IMAGE_NAME}" \
  -t "${IMAGE_NAME}:${VERSION}" \
  "${BUILD_CONTEXT}" || error "镜像构建失败"

# 添加标签
info "添加镜像标签: ${TAG}"
docker tag "${IMAGE_NAME}:${VERSION}" "${TAG}" || error "添加标签失败"

# 推送镜像
info "开始推送镜像到 ${TAG}"
docker push "${TAG}" || error "镜像推送失败"

# 清理本地临时镜像（可选）
if [ "${VERSION}" != "latest" ]; then
  info "清理临时镜像..."
  docker rmi "${IMAGE_NAME}:${VERSION}" "${TAG}" >/dev/null 2>&1 || true
fi

info "镜像构建并推送成功: ${TAG}"
